﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Ledict.ConditionExtract.Common;
using Ledict.ConditionExtract.Model;
using System.Text.RegularExpressions;

namespace Ledict.ConditionExtract.BLL.WorkProcess
{
    /// <summary>
    /// 再处理数据
    /// </summary>
    public class WorkThread_Second_Crime : WorkThread
    {
    
       
        public int MaxCount = 0;
        private int CurrentCount = 0;
       

        protected TreeDataBLL trbll = new TreeDataBLL();
        protected Ledict.ConditionExtract.BLL.Express_WordBLL wordbll = new Express_WordBLL();
        protected Ledict.ConditionExtract.BLL.Express_AddElement addelementbll = new Express_AddElement();
        protected ExpressGroupSituationBLL expresitu = new ExpressGroupSituationBLL();
        protected Express_MatchSituationBLL match = new Express_MatchSituationBLL();
        protected AboutRegexBLL aboutreg = new AboutRegexBLL();
        protected RegexParse.RegexParse getregex = new RegexParse.RegexParse();
        protected ProcessDataSourceBLL datas = new ProcessDataSourceBLL();
        protected WorkThread_Public work = new WorkThread_Public();
        protected XmlLabel_LabelRelBLL xmlLabel_LabelRelBLL = new XmlLabel_LabelRelBLL();
        CaseCauseBLL casecausebll = new CaseCauseBLL();
        StaticCacheBLL staticcache = new StaticCacheBLL();
        WorkThread_first_Crime workthread_first = new WorkThread_first_Crime();
        Express_WordBLL express_wordbll = new Express_WordBLL();


        /// <summary>
        /// 开始加工object  wordListObj（处理多个案由）
        /// </summary>
        public override void execute_Start()
        {
            getregex.StartCache();
          
            MaxCount += datas.GetDataSource_Second(conditon.SituationId).Rows.Count;//第一步 已处理过的表述

            if (!String.IsNullOrEmpty(conditon.HeadwordId))//第一级漏掉的数据
            {
                conditon.HeadwordId = trbll.GetHeadWordAllPid(conditon.HeadwordId);
                MaxCount += workthread_first.GetDataSourceCount(conditon);
            }
            #region 没数据进度条
            if (MaxCount == 0)   //没有可以跑数据的案例
            {
                if (MaxCount >= CurrentCount)
                {
                    processShow(MaxCount, CurrentCount);
                }
            }
            else
            {
                //加工
                execute_Condition(conditon);
            }
            #endregion

            getregex.EndCache();

        }
        /// <summary>
        /// （处理具体一个案由）
        /// </summary>
        /// <param name="conditon"></param>
        public virtual void execute_Condition(DataSourceCondition conditon)//案由ID
        {
            execute_Condition_One( conditon);//跑已存库的数据
            if (!String.IsNullOrEmpty(conditon.HeadwordId))
            {
                execute_Condition_Two(conditon);//跑第一次筛掉的数据
            }
         }

        public  void execute_Condition_One(DataSourceCondition conditon)//案由ID
        {
            DataTable Caseiddt = datas.GetDataSource_Second(conditon.SituationId);//第一步 已处理过的表述
            DataTable conditiondt;
            string ParagraphText = "";
            SYS_Express_AgainInfomation Model;
            for (int k = 0; k < Caseiddt.Rows.Count; k++)//数据
            {
                ParagraphText = Caseiddt.Rows[k]["ParagraphText"].ToString();

                Model = new Model.SYS_Express_AgainInfomation();
                Model.EW_ID = Caseiddt.Rows[k]["Id"].ToString();
                Model.CaseCauseID = Caseiddt.Rows[k]["CaseCauseID"].ToString();
                Model.ES_SituationIds = Caseiddt.Rows[k]["ES_SituationIds"].ToString();
                Model.ParagraphTypeId = Caseiddt.Rows[k]["ParagraphTypeId"].ToString();
                Model.CaseId = Caseiddt.Rows[k]["CaseId"].ToString();
                conditiondt = staticcache.GetHeadwordData(Model.CaseCauseID);      
                //做
                execute_Match(conditiondt, ParagraphText, conditon.SituationId, Model);
                #region 处理完成后,进度条
                CurrentCount++; // 显示进度条
                if (MaxCount >= CurrentCount)
                {
                    processShow(MaxCount, CurrentCount);
                }
                lockObj.WaitOne();
                #endregion
            }          
        }
        public void execute_Condition_Two(DataSourceCondition conditon)//案由ID
        {
            int PerPage = 5000;
            int page = (int)Math.Ceiling((double)MaxCount / PerPage);  

             string  ProcessNodeId="";
             string ParagraphID = "";
             string id = "";
             string caseid = "";
             string ParagraphText = "";
             DataTable conditiondt;//下级
             DataTable Caseiddt;
             DataTable ProcessNodedt;
             ProcessNodedt = work.BelongCaseCauseId(conditon.SituationId);//节点开始处
             #region 分页
             for (int pag = 1; pag <= page; pag++)
             {

                 Caseiddt = workthread_first.GetDataSource(conditon, pag, PerPage);//案由ID的相关文本数据(得到Caseid)
                 for (int k = 0; k < Caseiddt.Rows.Count; k++)//数据
                 {
                     for (int p = 0; p < ProcessNodedt.Rows.Count; p++)//小单元
                     {
                         //if (datas.Existsluceneid(Caseiddt.Rows[k]["id"].ToString(), ProcessNodeId))//跑过的案例
                         {
                             ProcessNodeId = ProcessNodedt.Rows[p]["CC_ID"].ToString();//节点开始处
                             ParagraphID = Caseiddt.Rows[k]["ParagraphTypeId"].ToString();
                             id = Caseiddt.Rows[k]["id"].ToString();
                             caseid = Caseiddt.Rows[k]["CaseId"].ToString();
                             ParagraphText = Caseiddt.Rows[k]["ParagraphText"].ToString();
                            //2017-6-21 ljj 修改，从索引中获取隐私处理数据
                            string fieldValue = Caseiddt.Rows[k]["FieldValue"].ToString();//row["FieldValue"].ToString();//
                            ParagraphText = Privacy(ParagraphText, fieldValue);//隐私处理

                            #region  提前筛选数据
                            bool flog = true;
                             conditiondt = staticcache.GetHeadwordData(ProcessNodeId);
                             DataRow[] arrayDRPro = conditiondt.Select("CC_ID='" + conditon.SituationId + "'");
                             if (arrayDRPro.Count() > 0 && Convert.ToInt32(arrayDRPro[0]["RegCount"].ToString()) > 0)//有正则
                             {
                                 if (ISMatch(ParagraphText, arrayDRPro[0]["CC_RegexInfoCode"].ToString()) > 0)
                                 {
                                     flog = true;
                                 }
                                 else
                                 {
                                     flog = false;
                                 }
                             }
                             #endregion

                             if (flog)
                             {
                                 //做
                             //    workthread_first.execute_Match(ParagraphText, caseid, ParagraphID, ProcessNodeId, conditiondt);
                                 //记状态
                                 datas.UpdateDataState(id, ProcessNodeId);//加工完，更新状态

                             }
                         }

                     }
                     #region 处理完成后,进度条

                     CurrentCount++; // 显示进度条
                     if (MaxCount >= CurrentCount)
                     {
                         processShow(MaxCount, CurrentCount);
                     }
                     lockObj.WaitOne();
                     if (readyToClose)
                     {
                         break;
                     }

                     #endregion
                 }
             }
             #endregion

        }

        #region 隐私处理
        /// <summary>
        /// 隐私处理
        /// </summary>
        /// <param name="ParagraphText"></param>
        /// <param name="CaseId"></param>
        /// <returns></returns>
        public string Privacy(string ParagraphText, string fieldValue)
        {
            #region 隐私处理
            //ParagraphText = "被告人谢荣兵已经着手实施盗窃犯罪，由于意志以外的原因而未得逞，系犯罪未遂。";
            //CaseId = "1000249";
            try
            {
                //2017-6-21 ljj 修改，不每次从数据库中获取隐私处理数据
                string Fields = fieldValue.Replace("，", ",");//datas.ExceptAdditionalFields(CaseId).Replace("，", ",");
                Fields = Fields.Replace(",", "|").Replace("，", "|").Replace("*", @"\*").Trim();//取人名
                if (Fields != "")
                {
                    ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, Fields, "×××");//挖空人名
                }
                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "[\\d,，一二三四五六七八九十万千百亿]+[百千万]?余?(?=元)", "***", RegexOptions.Singleline);
                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "(×××|\\*\\*\\*)[、|，|,]*(?=(×××|\\*\\*\\*))", "", RegexOptions.Singleline);

                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "^\\s*[“\"\\、……）\\]}】、,，。.：:；;\\d（\\(\\)） 两一二三四五六七八九但]*", "");
                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "^\\s*(本院认为|本院认为)[,:，：]*", "");
                ParagraphText = System.Text.RegularExpressions.Regex.Replace(ParagraphText, "[；|;]$", "。");
                //ParagraphText = getregex.GetParseValue("CC1508221657230001", ParagraphText);//排除金额，多×××
                //ParagraphText = getregex.GetParseValue("CC1508211030520001", ParagraphText);//排除某些字符
                return ParagraphText;//排除某些字符

            }
            catch (Exception error)
            {
                error.ToString();
                return ParagraphText;
            }
            #endregion
        }
        #endregion

        #region 加工处理
        public void execute_Match(DataTable conditiondt, string inputText, string NowAgainId, SYS_Express_AgainInfomation model)//第一层情形情节（conditiondt限定规则范围）
        {
            List<string> resultlist = new List<string>();
            IList<string> list = new List<string>();
            string EI_ID = "";
            string CC_ID = "";
            int Reg_Count = 0;
            int ChildCount = 0;
            string CC_IDListOld = "";//存储原不变关系
            string ResultText = "";//总的结果

            DataTable RelationStiuationdt;//下级
            if (StaticCacheBLL.RelationStiuationDict.ContainsKey(NowAgainId))
            {
                RelationStiuationdt = StaticCacheBLL.RelationStiuationDict[NowAgainId];
            }
            else
            {
                RelationStiuationdt = casecausebll.GetRelationStiuation(NowAgainId);
                StaticCacheBLL.RelationStiuationDict.Add(NowAgainId, RelationStiuationdt);
            }

            DataTable AllBelowStiuationdt;//当前节点父级及父级节点的所有下级
            if (StaticCacheBLL.AllBelowStiuationDict.ContainsKey(NowAgainId))
            {
                AllBelowStiuationdt = StaticCacheBLL.AllBelowStiuationDict[NowAgainId];
            }
            else
            {
                AllBelowStiuationdt = casecausebll.GetAllBelowStiuation(NowAgainId);
                StaticCacheBLL.AllBelowStiuationDict.Add(NowAgainId, AllBelowStiuationdt);
            }

            string AboutId = RelationStiuationdt.Rows[0]["AboutId"].ToString();
            string AllBelowId = AllBelowStiuationdt.Rows[0]["AllBelowId"].ToString();

            CC_IDListOld = System.Text.RegularExpressions.Regex.Replace("," + model.ES_SituationIds + ",", AboutId, ",");//去掉改节点相关的直系节点

            // CC_IDListOld = getregex.GetParseValue("CC1509171748560001", CC_IDListOld);//去掉多余逗号
            bool IsAddParentid = System.Text.RegularExpressions.Regex.IsMatch("," + CC_IDListOld + ",", AllBelowId);//匹配的话 代表有父级的下级节点  ;

            DataRow[] arrayDR = conditiondt.Select("CC_ID='" + NowAgainId + "'");
            if (arrayDR.Length > 0)
            {
                EI_ID = arrayDR[0]["CC_RegexInfoCode"].ToString();
                CC_ID = arrayDR[0]["CC_ID"].ToString();
                Reg_Count = Convert.ToInt32(arrayDR[0]["RegCount"].ToString());
                ChildCount = Convert.ToInt32(arrayDR[0]["ChildCount"].ToString());
                MatchChild(conditiondt, inputText, CC_ID, EI_ID, Reg_Count, ChildCount, ref ResultText);

                if (ResultText == "")   //自己没有，挂父级
                {
                    if (!IsAddParentid && arrayDR[0]["PidCC_IsProcessNode"].ToString() != "1")
                        ResultText = arrayDR[0]["CC_ParentID"].ToString();
                }

                ResultText += "," + CC_IDListOld; //加上原来的关系

                ResultText = getregex.GetParseValue("CC1509171748560001", ResultText);//去掉多余逗号
                if (ResultText.Trim() != "")
                {

                    string[] SituationStart = model.ES_SituationIds.Split(',');
                    string[] SituationEnd = ResultText.Split(',');
                    Array.Sort(SituationStart);
                    Array.Sort(SituationEnd);

                    if (!work.CompareArr(SituationStart, SituationEnd))//不一样
                    {
                        //删
                        express_wordbll.Delete_WordProcess(model.EW_ID);
                        //增 
                        work.AddToExpress(inputText, model.CaseId, model.ParagraphTypeId, model.CaseCauseID, ResultText);
                    }
                }
                else
                {
                    //删除
                    express_wordbll.Delete_WordProcess(model.EW_ID);
                }
            }
        }
        //非一层
        public bool MatchChild(DataTable conditiondt, string OneinputText, string CC_ID, string CC_RegexInfoCode, int Reg_Count, int ChildCount, ref string ResultText)//CC_ID 及以下是不是有匹配
        {
            int MatchNumber = 1;
            if (Reg_Count > 0)  //有正则
            {
                MatchNumber = ISMatch(OneinputText, CC_RegexInfoCode);
            }
            #region
            if (MatchNumber == 1)//匹配
            {
                bool child = false;
                if (ChildCount > 0)
                {
                    DataRow[] arrayDR = conditiondt.Select("CC_ParentID='" + CC_ID + "' and CC_NodeType<>12");
                    for (int i = 0; i < arrayDR.Length; i++)
                    {
                        bool mat = MatchChild(conditiondt, OneinputText, arrayDR[i]["CC_ID"].ToString(), arrayDR[i]["CC_RegexInfoCode"].ToString(), Convert.ToInt32(arrayDR[i]["RegCount"].ToString()), Convert.ToInt32(arrayDR[i]["ChildCount"].ToString()), ref ResultText);
                        if (mat)
                        {
                            child = true;
                        }
                    }
                }
                if (!child && Reg_Count > 0)//下级没有匹配到(没写数据不挂数据)
                {
                    if (ResultText == "")
                    {
                        ResultText = CC_ID;
                    }
                    else
                    {
                        ResultText += "," + CC_ID;
                    }
                }
                return true;
            }
            #endregion
            return false;
        }

        //正则是否匹配
        public int ISMatch(string inputText, string CC_RegexInfoCode)
        {
            if (getregex.IsMatch(CC_RegexInfoCode, inputText))//匹配 CC_RegexInfoCode为编号
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        #endregion

    }




    }










